package com.lucifer.d.security.exception.handler;

import com.lucifer.d.security.exception.AuthException;
import com.lucifer.d.security.exception.SecurityReqException;
import com.lucifer.d.security.exception.TokenException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Lucifer
 * @create 2023 - 03 - 05 16:55
 */
@RestControllerAdvice
public class SecurityExceptionHandler {

    @ResponseStatus(HttpStatus.CONFLICT)
    @ExceptionHandler(SecurityReqException.class)
    public @ResponseBody Map<String, Object> securityReqExceptionHandler(SecurityReqException sex) {
        Map<String, Object> resultMsg = new HashMap<>();
        resultMsg.put("statusCode", 409);
        resultMsg.put("message", sex.getMessage());
        return resultMsg;
    }

    @ResponseStatus(HttpStatus.FOUND)
    @ExceptionHandler(TokenException.class)
    public @ResponseBody Map<String, Object> tokenExceptionHandler(TokenException tex) {
        Map<String, Object> resultMsg = new HashMap<>();
        // token不存在或错误存在
        if (tex.getMessage().equals(TokenException.CODE302)) {
            resultMsg.put("statusCode", 302);
        }
        // token已过期
        else if (tex.getMessage().equals(TokenException.CODE303)) {
            resultMsg.put("statusCode", 303);
        }
        resultMsg.put("message", tex.getMessage());
        return resultMsg;
    }

    /**
     * 无权限异常返回处理
     *
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.PERMANENT_REDIRECT)
    @ExceptionHandler(AuthException.class)
    public @ResponseBody Map<String, Object> responseAuthorExceptionHandler(Exception ex) {
        Map<String, Object> resultMsg = new HashMap<>();
        resultMsg.put("statusCode", 308);
        resultMsg.put("message", ex.getMessage());
        return resultMsg;
    }

}
